/**
 * 
 */
package edu.zut.hb.software.sample.base.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import edu.zut.hb.software.sample.base.dao.GenericTreeDao;
import edu.zut.hb.software.sample.base.domain.BaseTreeEntity;
import edu.zut.hb.software.sample.base.service.GenericTreeManager;

/**
 * @author Mie
 *
 */
public class GenericTreeManagerImpl<T extends BaseTreeEntity<T, PK>, PK extends Serializable> extends GenericManagerImpl<T, PK> implements GenericTreeManager<T, PK>{

	protected GenericTreeDao<T, PK> treeDao;

	@Override
	public List<T> getAncestors(PK id) {
		List<T> ancestors = new ArrayList<T>();
		T entity = this.treeDao.findById(id).get();
		T parent = entity.getParent();
		while (parent != null) { // 追述祖先
			ancestors.add(parent);
			entity = parent;
			parent = entity.getParent();
		}
		return ancestors;
	}

	@Override
	public List<T> getChildren(PK id) {
		T entity = this.treeDao.findById(id).get();
		return entity.getChildren();
	}

	@Override
	public List<T> getDescendants(PK id) {
		List<T> descendants = new ArrayList<T>();
		List<T> children = this.getChildren(id);
		if (children != null && children.size() > 0) { // 追加子孙
			descendants.addAll(children);
			for (T t : children) {
				List<T> descendants2 = this.getDescendants(t.getId());
				descendants.addAll(descendants2);
			}
		}
		// if (children != null && children.size() > 0) {
		// descendants.addAll(children);
		// for (T t : children) {
		// @SuppressWarnings("unchecked")
		// List<T> descendants2 = this.getDescendants((PK) t.getId());
		// descendants.addAll(descendants2);
		// }
		// }
		return descendants;
	}

	@Override
	public List<T> getRoot() {
		return this.treeDao.getRoot();
	}

}
